package com.bwie.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.TbDictMapper;
import com.bwie.poi.ExcelUtil;
import com.bwie.poi.StringUtils;
import com.bwie.pojo.TbDict;
import com.bwie.pojo.TbPolicy;
import com.bwie.service.TbPolicyService;
import com.bwie.mapper.TbPolicyMapper;
import com.bwie.utils.Result;
import com.bwie.vo.PageInfoVo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lenovo
 * @description 针对表【tb_policy(红包策略表)】的数据库操作Service实现
 * @createDate 2025-06-07 11:01:11
 */
@Service
public class TbPolicyServiceImpl extends ServiceImpl<TbPolicyMapper, TbPolicy>
        implements TbPolicyService {

    @Autowired
    TbPolicyMapper tbPolicyMapper;
    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    TbDictMapper tbDictMapper;

    @Autowired
    HttpServletRequest request;

    @Autowired
    HttpServletResponse response;


    @Override
    public Result getPolicyList(PageInfoVo pageInfoVo) {

        Page<TbPolicy> page = new Page<>(pageInfoVo.getPageNum(), pageInfoVo.getPageSize());

        QueryWrapper<TbPolicy> wrapper = new QueryWrapper<>();

        if (StringUtils.isNotEmpty(pageInfoVo.getKeyWord())) {
            wrapper.lambda().like(TbPolicy::getPolicyName, pageInfoVo.getKeyWord());
        }

        if (pageInfoVo.getTypeId() != null) {
            wrapper.lambda().eq(TbPolicy::getPacketEnable, pageInfoVo.getTypeId());
        }
        //排序
        wrapper.lambda().orderByDesc(TbPolicy::getCreateTime);

        Page<TbPolicy> tbPolicyPage = tbPolicyMapper.selectPage(page, wrapper);

        String token = request.getHeader("token");
        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        Integer userId = body.get("userId", Integer.class);
        String key = "policy" + userId;
        redisTemplate.opsForValue().set(key, JSON.toJSONString(tbPolicyPage.getRecords()));

        return Result.ok().setData(tbPolicyPage);
    }

    @Override
    public Result getDictList(Integer typeId) {

        //检查缓存中是否存在
        String key = "dict-" + typeId;
        Boolean hasKey = redisTemplate.hasKey(key);
        if (hasKey) {
            List<Object> values = redisTemplate.opsForHash().values(key);
            //对象转换
            List<TbDict> dictList = values.stream().map(item -> {
                TbDict tbDict = JSON.parseObject(item.toString(), TbDict.class);
                return tbDict;
            }).collect(Collectors.toList());
            return Result.ok().setData(dictList);
        }

        //不存在从数据库读取
        List<TbDict> tbDictList = tbDictMapper.selectList(
                new QueryWrapper<TbDict>().lambda().eq(TbDict::getDictType, typeId)
        );

        for (TbDict tbDict : tbDictList) {
            String key1 = "dict-" + typeId;
            String key2 = tbDict.getDictValue().toString();
            String value = JSON.toJSONString(tbDict);

            redisTemplate.opsForHash().put(key1, key2, value);
        }
        return Result.ok().setData(tbDictList);

    }

    @Override
    public void exportPacketList(Integer userId) {

        String key = "policy-" + userId;
        String s = redisTemplate.opsForValue().get(key);
        List<TbPolicy> tbPolicies = JSON.parseArray(s, TbPolicy.class);
        ExcelUtil<TbPolicy> excelUtil = new ExcelUtil<>(TbPolicy.class);
        excelUtil.exportExcel(response, tbPolicies, "红包策略列表");
    }

    @Override
    public Result onAddPolicy(TbPolicy tbPolicy) {


        long beginTime = tbPolicy.getBeginTime().getTime();
        long endTime = tbPolicy.getEndTime().getTime();
        if ((endTime - beginTime) < 1000 * 60 * 60 * 24) {
            return Result.error().setMsg("策略结束时间应该在生效时间的一天后");
        }

        tbPolicyMapper.insert(tbPolicy);
        return Result.ok();
    }
}




